<?php
namespace app\Test\controller;



use app\admin\model\AdminRole;
use app\admin\model\MenuModel;
use think\Controller;
use think\Db;
use think\Response;

class Index extends Controller
{
    public function index() {
        $role_id = 10;
        $menu_auth = 27;
//        $res = $this->setRoleMenuAuth( $role_id, $menu_auth );
       /* $res['exp'] = explode(',', $menu_auth);
        $res['other'] = array(1,2,3);*/
        $menu = MenuModel::select();
        $parents = MenuModel::getParents($menu, 298);
        $self = array_pop($parents);
        $res = MenuModel::getSpecialSiblings($menu, $self['parent_id']);
        Response::create($res, 'json')->send();
    }

    function testDel( $lists, $pid ) {
        $trees = [];
        $num = 0;
        $oneNode = '';
        foreach ($lists as $value) {
            if ($value['parent_id'] == $pid) {
                $trees[] = $value;
                $num++;
            }
            if ( $value['id'] == $pid ) {
                $oneNode = $value;
            }
        }

        if ( $num <= 1 && $oneNode) {
            $this->testDel($lists, $oneNode['parent_id']);
            $trees   = array_merge(array($oneNode), $trees);
        } else {
            $trees = [];
        }

        return $trees;
    }

    /*
     * 设置角色菜单权限
     * @param int $role_id 角色ID
     * @param string $menu_auth 菜单权限
     *
     * */
    function setRoleMenuAuth( $role_id, $menu_auth ) {
        $menu = MenuModel::select()->toArray();
        $parents = MenuModel::getParents( $menu, $menu_auth);
        $childrens = MenuModel::getChildren( $menu, $menu_auth);
        $allMenu = array_column( array_merge( (array)$parents, (array)$childrens ), 'id');
//        $inAllKey = array_search( $menu_auth, $allMenu );

        $role = AdminRole::get($role_id);
        $menuAuth = (array)$role->menu_auth;
        /*$inRoleKey = array_search( $menu_auth, $menuAuth );

        if ( array_search( $menu_auth, $allMenu ) ) {

        }*/
        $roleMenuAuth = array_unique( array_merge($menuAuth, $allMenu) );
        return $roleMenuAuth;
    }

    function tabs() {
        return $this->fetch();
    }


}
